package org.example.dingtalkintegrationservice.filter;

import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.UUID;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.slf4j.MDC;

import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;





/**
 * 记录请求日志
 */
@Slf4j
public class RequestLogFilter extends HttpFilter {

//    @Resource
//    HttpLogRepository httpLogRepository;

    /**
     *
     */
    private static final long serialVersionUID = 8991118181953196532L;


    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException {

        String requestId=UUID.randomUUID().toString();
        MDC.put("requestId", requestId);

        // Wrapper 封装 Request 和 Response
        ContentCachingRequestWrapper cachingRequest = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper cachingResponse = new ContentCachingResponseWrapper(response);
        // 继续执行请求链
        Throwable e=new Exception();
        try{
            chain.doFilter(cachingRequest, cachingResponse);
    }
        catch (ServletException e1){
//            e=e1.getStackTrace();
        e=e1.getCause();
           throw (RuntimeException)e;

        }
//        catch (UndeclaredThrowableException e2){
//            log.error("e2");
//            System.out.println(e2.getCause().getMessage());
//        }
//        catch (Exception e3){
//            System.out.println(e3.getClass());
//            throw (RuntimeException)e3.getCause();
//        }
            finally {
            String method = request.getMethod();
            // URI
            String uri = request.getRequestURI();
            String queryString=request.getQueryString();
            int status = response.getStatus();
            // 响应体
            byte[] responseContent = cachingResponse.getContentAsByteArray();

            // 请求体
            byte[] requestContent = cachingRequest.getContentAsByteArray();

//        httpLogRepository.save(httpLog);
            // 请求方法
            if (status==200) {
                log.info("RequestId : {}", requestId);
                log.info("RequestMethod : {}", method);
                log.info("RequestURI : {}", uri);
                log.info("RequestQueryString: {}", queryString);
                log.info("RequestBody : {}", new String(requestContent));
                log.info("ResponseStatus : {}", status);
                log.info("ResponseResult:{}", new String(responseContent));
            }
            else {
                log.warn("RequestId : {}",requestId);
                log.warn("RequestMethod : {}", method);
                log.warn("RequestURI : {}",uri);
                log.warn("RequestQueryString: {}",queryString);
                log.warn("RequestBody : {}",new String(requestContent));
                log.warn("ResponseStatus : {}", status);
                log.warn("ResponseResult:{}", new String(responseContent));
                log.warn(e.getMessage());
            }
            cachingResponse.copyBodyToResponse();
        }

    }
}